<template>
  <el-table ref="tableRef" :data="data" border style="width: 100%" @select="handleSelectChange"
    @selection-change="handleSelectionChange" v-horizontal-scroll="'always'">
    <!-- 多选 -->
    <el-table-column v-if="config.showSelection" type="selection" width="55" align="center" />

    <!-- 操作列 -->
    <el-table-column v-if="$.isNotNull(config.operations)" :label="config.operations.label"
      :width="config.operations.width" align="center">
      <template #default="operationsScope">
        <el-button v-for="(item, index) in config.operations.operations(
          operationsScope.row
        )" :key="index" size="small" type="primary" text @click="$emit('operationsHander', item, operationsScope.row)">
          {{ item.label }}
        </el-button>
      </template>
    </el-table-column>

    <!-- 序号 -->
    <el-table-column v-if="config.showIndex" type="index" label="序号" :index="indexMethod" width="60" align="center" />

    <!-- 数据列 -->
    <el-table-column v-for="(column, index) in config.column" :key="index" :prop="column.prop" :label="column.label"
      :width="column.width" align="center" :min-width="150">
      <template v-if="column.type === COLUMN_TYPE.picture" #default="scope">
        <img :src="scope.row[column.prop]" :style="{
          width: column.width - 25 + 'px',
          height: column.width - 25 + 'px',
        }" />
      </template>
      <template v-else-if="column.type === COLUMN_TYPE.switch" #default="scope">
        <el-switch v-model="scope.row[column.prop]" inline-prompt :active-text="column.activeText"
          :inactive-text="column.inactiveText" :active-value="column.activeValue" :inactive-value="column.inactiveValue"
          size="large" :width="column.switchWidth" :before-change="switchBeforeChange(scope.row, column.operationsKey)" />
      </template>
      <template v-else-if="column.type === COLUMN_TYPE.input" #default="scope">
        <el-input type="number" onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')" v-model.number="scope.row[column.prop]"
          @change="
            (val) => {
              $emit('operationsHander', column.operationsKey, {
                value: val,
                data: scope.row,
              });
            }
          " />
      </template>
      <template v-else-if="column.type === COLUMN_TYPE.inputPrice" #default="scope">
        <el-input-number v-model.number="scope.row[column.prop]" :min="0" :precision="2" :controls="false"
          controls-position="right" @change="
            (val) => {
              $emit('operationsHander', column.operationsKey, {
                value: val,
                data: scope.row,
              });
            }
          " />

      </template>
      <template v-else-if="column.type === COLUMN_TYPE.linkText" #default="scope">
        <p style="cursor: pointer;" @click="$emit('operationsHander', column.operationsKey, scope.row)">
          {{ scope.row[column.prop] }}
        </p>
      </template>
      <template v-else-if="column.type === COLUMN_TYPE.tooltip" #default="scope">
        <el-tooltip :content="scope.row[column.prop]" popper-class="table_tooltip_desc" placement="top">
          <p class="descStyle;cursor: pointer;" :style="{ '-webkit-line-clamp': column.rows }">
            {{ scope.row[column.prop] }}
          </p>
        </el-tooltip>
      </template>
      <template v-else-if="column.type === COLUMN_TYPE.depositMoney" #default="scope">
        <p style="cursor: pointer;" @click="$emit('operationsHander', column.operationsKey, scope.row)">
          {{ scope.row[column.prop] }}
        </p>
      </template>
      <template v-else-if="column.type === COLUMN_TYPE.freezeMoney" #default="scope">
        <p style="cursor: pointer;" @click="$emit('operationsHander', column.operationsKey, scope.row)">
          {{scope.row[column.prop] }}
        </p>
      </template>
      <template v-else #default="scope">
        <p>{{scope.row[column.prop] }}</p>
      </template>
    </el-table-column>
  </el-table>
  <div class="pagination_layout">
    <el-pagination background layout="total, prev, pager, next, sizes" :total="total" v-model:currentPage="page"
      v-model:page-size="size" :page-sizes="[10, 20, 50, 100]" @current-change="pagerChange"
      @size-change="pagerSizeChange" />
  </div>
</template>
<script setup>
import $ from "@util/base";
import { defineProps, defineEmits, ref, watch, defineExpose } from "vue";
import { COLUMN_TYPE } from "./tableOperations";
import useRoute from "@util/router";
import defaultPage from "@api/page";
const route = useRoute();
const props = defineProps({
  /**
   * config:{
   *      showSelection:false,
   *      showIndex:false,
   *      operations:{
   *          label:'操作',       操作列名，如果没有设置则不显示操作栏
   *          width:200,         操作列宽度
   *          operations:[        操作列表
   *              {
   *                  key:1,
   *                  label:'修改',
   *                  color:'#ffffff'
   *              }
   *          ]
   *      },
   *      column:[ 列配置
   *          {
   *              label:'姓名',   列名
   *              prop:'name',   列数据字段
   *              width:180,     列宽度
   *          }
   *      ]
   * }
   */
  config: Object,
  data: Array, //数据源
  total: { type: Number, default: 0 }, //总条数
  isRoute: { type: Boolean, default: true }, // 分页切换是否上路由 需要配合pageChange
  isRadio: { type: Boolean, default: false }, // 是否是单选
});
let routeQuery = route.query();
const size = ref(routeQuery.s ? parseInt(routeQuery.s) : defaultPage.size);
const page = ref(routeQuery.p ? routeQuery.p : 1);
const data = ref(props.data || []);
const total = ref(props.total);

watch(
  () => props.data,
  (val) => {
    data.value = val;
  }
);
watch(
  () => props.total,
  (val) => {
    total.value = val;
  }
);
// watch(
//   () => route.params,
//   (val) => {
//     console.log(val)
//     if (val.s) {
//       size.value = val.s
//     }
//     if (val.p) {
//       page.value = val.p
//     }
//   }
// );
/**
 * 操作列 操作按钮事件,
 * operationsHander(type,rowData)
 * 分页栏 事件
 * pageChange
 */
const emit = defineEmits(["operationsHander", "pageChange"]);

function indexMethod(index) {
  return (page.value - 1) * size.value + index + 1;
}

function pagerChange(val) {
  if (props.isRoute) {
    route.replaceQuery("p", val);
  } else {
    emit("pageChange", "page", val);
  }
}
function pagerSizeChange(val) {
  if (props.isRoute) {
    route.replaceQuery("s", val);
  } else {
    emit("pageChange", "size", val);
  }
}

function switchBeforeChange(val, key) {
  return () => {
    return new Promise((resolve, reject) => {
      emit("operationsHander", key, {
        data: val,
        resolve: resolve,
        reject: reject,
      });
    });
  };
}

const tableRef = ref(null);

var selectData = [];
function handleSelectionChange(val) {
  selectData = val;
}

function handleSelectChange(selection, row) {
  if (props.isRadio) {
    if (selection.length > 1) {
      clearSelection();
      tableRef.value.toggleRowSelection(selection.pop());
    }
  }
}

function getSelectData() {
  return selectData;
}

function clearSelection() {
  tableRef.value.clearSelection();
}

defineExpose({ getSelectData, clearSelection });
</script>

<style scoped>
.pagination_layout {
  display: flex;
  justify-content: flex-end;
  margin-top: 40px;
  margin-bottom: 10px;
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}

::v-deep input[type="number"] {
  -moz-appearance: textfield !important;
}

.descStyle {
  display: -webkit-box;
  overflow: hidden;
  white-space: normal !important;
  text-overflow: ellipsis;
  word-wrap: break-word;
  /* -webkit-line-clamp: 3; */
  -webkit-box-orient: vertical;
}

.el-button--small {
  font-size: 16px;
  margin: 0 0 5px 5px;
}
</style>

<style>
.table_tooltip_desc {
  max-width: 300px !important;
}

.el-scrollbar__bar.is-horizontal {
  height: 10px !important;
}

/* .el-scrollbar{
  --el-scrollbar-bg-color:#666;
  --el-scrollbar-hover-bg-color:#444;
} */
</style>
